<?php

namespace Tasker\Components;

class TaskControl extends BaseControl
{

	public function renderMyTasks()
	{
		$this->setTemplate();
		$tasks = $this->presenter->context->models->tasks;
		$ownTasksCount = $tasks->getTasksCount($this->getPresenter()->getUser()->getId());
		$this->template->ownTasksCount = $ownTasksCount;

		$ownTasks = $tasks->getTasks($this->getPresenter()->getUser()->getId())->order('IF(ISNULL(userpriority), 1, 0), userpriority');
		$this->template->ownTasks = $ownTasks;

		$priority = $this->presenter->context->models->taskContext;
		$this->template->priorities = $priority->getPriorities();

		$this->template->render();
	}

	public function renderAssignedTasks()
	{
		$this->setTemplate();
		$tasks = $this->presenter->context->models->tasks;

		$assignedTasksCount = $tasks->getAssignedTasksCount($this->getPresenter()->getUser()->getId());
		$this->template->assignedTasksCount = $assignedTasksCount;

		$assignedTasks = $tasks->getAssignedTasks($this->getPresenter()->getUser()->getId());
		$this->template->assignedTasks = $assignedTasks;

		$priority = $this->presenter->context->models->taskContext;
		$this->template->priorities = $priority->getPriorities();

		$this->template->render();
	}

	public function renderWatchedTasks()
	{
		$this->setTemplate();
		$tasks = $this->presenter->context->models->tasks;

		$watchedTasks = $tasks->getWatchedTasks($this->getPresenter()->getUser()->getId());
		$watchedTasksCount = count($watchedTasks);
		$this->template->watchedTasks = $watchedTasks;
		$this->template->watchedTasksCount = $watchedTasksCount;

		$priority = $this->presenter->context->models->taskContext;
		$this->template->priorities = $priority->getPriorities();

		$this->template->render();
	}

	protected function createTemplate($class = NULL)
	{
		$template = parent::createTemplate();
		$template->registerHelper('remaining_days', function($s)
				{
					$remaining = ceil((strtotime($s) - time()) / 60 / 60 / 24);
					if ($remaining == 0)
						$remaining = 0; // avoid -0 :)
					$str = "dnů";
					if (abs($remaining) == 1)
						$str = "den";
					if (abs($remaining) > 1 && abs($remaining) < 5)
						$str = "dny";
					if ($remaining > 7)
						$class = 'task_ok';
					elseif ($remaining >= 0)
						$class = 'task_hurry';
					else
						$class='task_late';
					return '<span class="' . $class . '">' . $remaining . " " . $str . '</span>';
				});
		return $template;
	}

	public function handleUpdateCompleted($task, $completed)
	{
		
	}
}
